/**
 * 腾讯云短信客户端
 */

const tencentcloud = require('tencentcloud-sdk-nodejs')
const config = require('../config/config')

// 导入腾讯云短信SDK
const SmsClient = tencentcloud.sms.v20210111.Client

class TencentSmsClient {
  constructor() {
    // 实例化认证对象
    const credential = {
      secretId: config.tencentCloud.secretId,
      secretKey: config.tencentCloud.secretKey
    }

    // 实例化客户端配置对象
    const clientConfig = {
      credential: credential,
      region: config.tencentCloud.region,
      profile: {
        httpProfile: {
          endpoint: 'sms.tencentcloudapi.com'
        }
      }
    }

    // 实例化SMS客户端
    this.client = new SmsClient(clientConfig)
  }

  /**
   * 发送短信验证码
   * @param {string} phone 手机号
   * @param {string} code 验证码
   * @returns {Promise} 发送结果
   */
  async sendVerifyCode(phone, code) {
    // 构造请求参数
    const params = {
      SmsSdkAppId: config.tencentCloud.sdkAppId,
      SignName: config.tencentCloud.signName,
      TemplateId: config.tencentCloud.templateId,
      TemplateParamSet: [code], // [验证码]
      PhoneNumberSet: [`+86${phone}`]
    }

    try {
      const response = await this.client.SendSms(params)
      console.log('腾讯云短信发送响应:', JSON.stringify(response, null, 2))

      // 检查发送状态
      if (response.SendStatusSet && response.SendStatusSet.length > 0) {
        const status = response.SendStatusSet[0]
        if (status.Code === 'Ok') {
          return {
            success: true,
            message: '短信发送成功',
            serialNo: status.SerialNo
          }
        } else {
          return {
            success: false,
            message: status.Message || '短信发送失败',
            code: status.Code
          }
        }
      }

      return {
        success: false,
        message: '短信发送响应格式异常'
      }
    } catch (error) {
      console.error('腾讯云短信发送失败:', error)
      return {
        success: false,
        message: error.message || '短信发送异常'
      }
    }
  }
}

module.exports = TencentSmsClient

